// service.js
const WebSocket = require('ws');

// 启动 WebSocket 服务，监听地址 ws://localhost:8091/ws/fastNews
const wss = new WebSocket.Server({
  port: 8091,
  path: '/ws/fastNews'
}, () => {
  console.log('✅ WebSocket Server running at ws://localhost:8091/ws/fastNews');
});

/* // 初始快讯数据
const initialNews = [
  {
    id: '136622',
    publishTime: '2025-05-29 15:34:39',
    title: '摩根士丹利将英伟达目标股价从160美元上调至170美元',
    url: 'https://finance.eastmoney.com/a/202505293417897326.html'
  },
  {
    id: '136623',
    publishTime: '2025-05-29 15:33:07',
    title: '奇瑞整合相关业务 成立“奇瑞智能化中心”',
    url: 'https://finance.eastmoney.com/a/202505293417896922.html'
  },
  {
    id: '136624',
    publishTime: '2025-05-29 15:32:18',
    title: '京东与小红书推出“红京计划”',
    url: 'https://finance.eastmoney.com/a/202505293417896667.html'
  },
  {
    id: '136625',
    publishTime: '2025-05-29 15:31:38',
    title: '商务部回应欧盟对中国轮胎产品发起反倾销调查：坚决维护中国企业合法权益',
    url: 'https://finance.eastmoney.com/a/202505293417896254.html'
  }
]; */

// 模拟生成一条“新快讯”
const generateNewNews = () => {
  const now = new Date();
  const timestamp = now.getTime();
  const id = `${timestamp}-${Math.floor(Math.random() * 5000)}`;
  const titles = [
    '小米汽车上市后订单量突破10万',
    '美联储加息预期降低，纳指上涨超2%',
    '字节跳动推出全新AI搜索引擎',
    '阿里云宣布全面开放通义大模型',
    '腾讯发布新一代AI数字人平台'
  ];

  const title = titles[Math.floor(Math.random() * titles.length)];

  return {
    id: id, // 使用时间戳+随机数作为唯一ID
    publishTime: now.toISOString().replace('T', ' ').substring(0, 19),
    title,
    url: `https://finance.eastmoney.com/a/${id}.html`
  };
};

// 批量生成3-5条新闻，一次性推送
const generateBatchNews = (count = 1) => {
  const newsList = [];
  for (let i = 0; i < count; i++) {
    newsList.push(generateNewNews());
  }
  return newsList;
};

// 构造初始化快讯数据
const mockNews = () => ({
  type: 'news',
  payload: initialNews
});

// WebSocket 客户端连接处理
wss.on('connection', (ws) => {
  // 首次仅推送初始列表
  ws.send(JSON.stringify(mockNews()));

  // 每5秒推送一条新消息
  const newsTimer = setInterval(() => {
    const newNews = generateNewNews();
    initialNews.unshift(newNews);

    // 控制只保留最近100条
    if (initialNews.length > 100) {
      initialNews.pop();
    }

    const message = {
      type: 'news',
      payload: [newNews]
    };

    // 检查连接状态，只有在连接打开时推送
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify(message));
      // 移除每次推送的日志
    } else {
      // 保留警告日志
      console.warn('⚠️ WebSocket未连接，无法推送消息');
    }
  }, 5000);

  // 添加心跳检测
  const heartbeatTimer = setInterval(() => {
    wss.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({ type: 'ping' }));
      }
    });
  }, 30000);

  ws.on('close', () => {
    clearInterval(newsTimer);
    clearInterval(heartbeatTimer);
    // 简化断开连接日志
    console.log('❌ Client disconnected');
  });

  ws.on('error', (err) => {
    // 保留错误日志
    console.error('WebSocket error:', err);
  });
});
